﻿var recordFormVue = new Vue({
    el: "#recordForm",
    data: {
        isNewRecord: true,          //判断是否为新纪录
        record: {                   //保养记录格式
            BaseInfo: {},
            Equipment: {
                BaseInfo: {},
                MaintainInfo: {}
            },
            TemplateForm: {
                BaseInfo: {},
                Items: []
            },
            ItemRecords: [],
            CheckerInfo: {},
            ApproverInfo: {}
        },
        templateFormList: [],       //保养单模板列表
        statusDictionary: {}        //设备状态字典
    },
    methods: {
        GetEquipment: function () {
            GetEquipmentByCode(this, this.record.Equipment.BaseInfo.Code);
        },
        GetCheckerInfo: function () {
            GetCheckerInfoByName(this, this.record.CheckerInfo.Name);
        },
        GetTemplateForm: function () {
            GetTemplateFormByID(this, this.record.TemplateForm.BaseInfo.ID);
        },
        BatchItemCheck: function (event) {
            event.preventDefault();
            $(".item-pass-btn").each(function () {
                this.click();
            });
        },
        ItemCheck: function (event, index, isPass) {
            event.preventDefault();
            ItemRecordCheck(this, index, isPass);
        },
        ItemRemark: function (event, index) {
            event.preventDefault();
            ItemRecordRemark(this, index, $(event.target).val());
        },
        SaveRecord: function (event) {
            event.preventDefault();
            SaveMaintainRecord(this);
        },
        UpdateRecord: function (event) {
            event.preventDefault();
            UpdateMaintainRecord(this);
        },
        ScanQrcode: function (event) {
            event.preventDefault();
            if (window.android != null && typeof (window.android) != "undefined") {
                window.android.showScanKit("handleAnroidScanKitCallback");
            } else {
                alert(typeof (window.android));
            }
        },
        Signout: function (event) {
            event.preventDefault();
            //登出功能，临时用于安卓手机
            document.location = "/Account/Login?ReturnUrl=/Maintain/Page/RecordDetail?IsNew=true";

        }
    },
    created: function () {
        //页面加载前初始的数据
        InitialAztechScript();
    },
    mounted: function () {
        var vue = this;
        //页面加载后初始的数据
        InitMaintainRecord(this);

        //设置保养日期时间选择器
        $("#recordDatePicker").datetimepicker({
            format: "yyyy-mm-dd",
            autoclose: true,
            minView: 2
        });
        //由于datetimepicker插件不能让Vue双向绑定数据生效，所以需监听事件赋值
        $("#recordDatePicker").datetimepicker().on("hide", function (event) {
            vue.record.BaseInfo.RecordDate = $(event.target).val();
            CheckRecordDate(vue);
        });
    }
});

/**
 * 处理安卓扫描返回结果
 */
function handleAnroidScanKitCallback(value) {
    document.location = "/Maintain/Page/RecordDetail?IsNew=true&EquipmentCode=" + value;
}

/**
 * 设置保养日期
 */
function GetRecordDate(vue, targetDate) {
    vue.record.BaseInfo.RecordDate = targetDate;
}

/**
 * 初始化保养单状态
 */
function InitMaintainRecord(vue) {
    var isNew = GetQueryString("IsNew");
    var recordID = GetQueryString("RecordID");
    var equipmentID = GetQueryString("EquipmentID");
    var equipmentCode = GetQueryString("EquipmentCode");
    var checkerID = GetQueryString("CheckerID");

    vue.statusDictionary = GlobalDictionary.GetEquipmentStatusDictionary();
    if (isNew == "true") {
        vue.isNewRecord = true;
        GetEquipmentByID(vue, equipmentID);
        if (equipmentCode != null) {
            GetEquipmentByCode(vue, equipmentCode);
        }
        if (checkerID == null) {
            checkerID = GlobalUser.getUserInfo().ID;
        }
        GetCheckerInfoByID(vue, checkerID);
        GetRecordDate(vue, new Date().Format("yyyy-MM-dd"));
    } else {
        vue.isNewRecord = false;
        GetMaintainRecordByID(vue, recordID);
    }
}

/**
 * 根据ID查询保养记录
 */
function GetMaintainRecordByID(vue, recordID) {
    parent.ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Maintain/GetMaintainRecordByID?RecordID=" + recordID + "&v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                vue.record = res.data;
                vue.record.BaseInfo.RecordDate = CSharpToJsDate(vue.record.BaseInfo.RecordDate)

                vue.$nextTick(function () {
                    //获取该设备所有保养单模板
                    GetTemplateFormListByEquipmentTypeID(vue, vue.record.Equipment.BaseInfo.TypeID);
                    //设置所有保养项目状态
                    for (var idx in vue.record.ItemRecords) {
                        ItemRecordCheck(vue, idx, vue.record.ItemRecords[idx].IsOk);
                        ItemRecordRemark(vue, idx, vue.record.ItemRecords[idx].Remark);
                    }
                    parent.ResizeAzModal();
                });

            } else {
                toastr.error(res.message);
            }
            parent.HideAzLoading();
        },
        error: function (err) {
            console.log(err);
            parent.HideAzLoading();
            toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
        }
    })
}

/**
 * 保存保养记录
 */
function SaveMaintainRecord(vue) {    
    if (CheckMaintainRecode(vue)) {
        parent.ShowAzLoading();
        $("button").attr("disabled", true);
        $.ajax({
            type: "POST",
            url: "/Maintain/SaveMaintainRecord",
            data: { record: vue.record },
            success: function (res) {
                if (res.status == "Success") {
                    toastr.success("保存保养记录成功Maintenance record saved successfully。");
                    ResetForm(vue);
                    InitMaintainRecord(vue);
                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            },
            complete: function () {
                parent.HideAzLoading();
                $("button").removeAttr("disabled");
            }
        })
    }
}

/**
 * 更新保养记录
 */
function UpdateMaintainRecord(vue) {
    if (CheckMaintainRecode(vue)) {
        parent.ShowAzLoading();
        $("button").attr("disabled", true);
        $.ajax({
            type: "POST",
            url: "/Maintain/UpdateMaintainRecord",
            data: { record: vue.record },
            success: function (res) {
                if (res.status == "Success") {
                    toastr.success("更新保养记录成功Maintenance record updated successfully。");
                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            },
            complete: function () {
                parent.HideAzLoading();
                $("button").removeAttr("disabled");
            }
        })
    }
}

/**
 * 根据用户ID查询负责（保养）人用户信息
 */
function GetCheckerInfoByID(vue, userID) {
    if (userID != null && userID > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Account/GetUserByID?userID=" + userID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    //设置负责（保养）员信息
                    vue.record.CheckerInfo = res.data;
                    vue.record.BaseInfo.CheckerID = vue.record.CheckerInfo.ID;
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    } else {
        vue.record.CheckerInfo = {};
    }
}

/**
 * 根据用户ID查询管理（签核）员用户信息
 */
function GetApproverInfoByID(vue, userID) {
    if (userID != null && userID > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Account/GetUserByID?userID=" + userID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    //设置管理（签核）员信息
                    vue.record.ApproverInfo = res.data;
                    vue.record.BaseInfo.ApproverID = vue.record.ApproverInfo.ID;
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    } else {
        vue.record.CheckerInfo = {};
    }
}

/**
 * 根据用户名查询保养员信息
 */
function GetCheckerInfoByName(vue, userName) {
    if (userName != null && userName.length > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Account/GetUserByName?userName=" + userName + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    //设置保养员信息
                    vue.record.CheckerInfo = res.data;
                    vue.record.BaseInfo.CheckerID = vue.record.CheckerInfo.ID;
                    $("#checkerName").removeClass("has-error");
                } else {
                    toastr.error(res.message);
                    vue.record.CheckerInfo = {};
                    $("#checkerName").addClass("has-error");
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    } else {
        vue.record.CheckerInfo = {};
    }
}

/**
 * 根据设备ID查询设备详细信息
 */
function GetEquipmentByID(vue, equipmentID) {
    if (equipmentID != null && equipmentID > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Equipment/GetEquipmentByID?EquipmentID=" + equipmentID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    //设置设备信息
                    vue.record.Equipment = res.data;
                    //如果设备为已报废，则不需要保养
                    if (vue.record.Equipment.BaseInfo.Status > 0) {
                        vue.record.BaseInfo.EquipmentID = vue.record.Equipment.BaseInfo.ID;
                        //获取设备类型对应的保养单模板
                        GetTemplateFormListByEquipmentTypeID(vue, vue.record.Equipment.BaseInfo.TypeID);
                        //获取设备管理(签核)人信息
                        GetApproverInfoByID(vue, vue.record.Equipment.BaseInfo.ManagerID);
                    } else {
                        toastr.error("设备已经报废，不需要保养，请检查！The equipment has been scrapped and does not need maintenance. Please check it!");
                    }
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    } else {
        vue.record.Equipment = {
            BaseInfo: {},
            MaintainInfo: {}
        };
    }
}

/**
 * 根据设备编号查询设备详细信息
 */
function GetEquipmentByCode(vue, equipmentCode) {
    if (equipmentCode != null && equipmentCode.length > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Equipment/GetEquipmentByCode?EquipmentCode=" + equipmentCode + "&v=" + Math.random(), 
            success: function (res) {
                if (res.status == "Success") {
                    //设置设备信息
                    vue.record.Equipment = res.data;
                    //如果设备为已报废，则不需要保养
                    if (vue.record.Equipment.BaseInfo.Status > 0) {
                        vue.record.BaseInfo.EquipmentID = vue.record.Equipment.BaseInfo.ID;
                        //获取设备类型对应的保养单模板
                        GetTemplateFormListByEquipmentTypeID(vue, vue.record.Equipment.BaseInfo.TypeID);
                        //获取设备管理(签核)人信息
                        GetApproverInfoByID(vue, vue.record.Equipment.BaseInfo.ManagerID);
                    } else {
                        toastr.error("设备已经报废，不需要保养，请检查！The equipment has been scrapped and does not need maintenance. Please check it!");
                    }
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    } else {
        vue.record.Equipment = {
            BaseInfo: {},
            MaintainInfo: {}
        };
    }
}

/**
 * 根据设备类型ID获取该类型的所有保养单模板
 */
function GetTemplateFormListByEquipmentTypeID(vue, equipmentTypeID) {
    if (CheckEquipment(vue)) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Maintain/ListTemplateFormByEquipmentTypeID?IsDisable=false&TypeID=" + equipmentTypeID + "&v=" + Math.random(), 
            success: function (res) {
                if (res.status == "Success") {
                    //设置对应设备可选保养单模板
                    vue.templateFormList = res.data;

                    //如果是新纪录则默认第一保养单模板
                    if (vue.isNewRecord) {
                        vue.$nextTick(function () {
                            if (vue.templateFormList.length > 0) {
                                vue.record.TemplateForm.BaseInfo.ID = vue.templateFormList[0].ID;
                                //获得第一保养单模板对应保养项目
                                GetTemplateFormByID(vue, vue.record.TemplateForm.BaseInfo.ID);
                            }
                        });
                    }
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    }
}


/**
 * 根据ID查询保养单模板详细（包含对应保养项目）
 */
function GetTemplateFormByID(vue, formID) {
    if (formID != null && formID > 0) {
        parent.ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Maintain/GetTemplateFormByID?FormID=" + formID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    vue.record.TemplateForm = res.data;
                    vue.record.BaseInfo.FormID = vue.record.TemplateForm.BaseInfo.ID;

                    //初始保养记录的ItemRecords
                    //重置项目输入框初始状态
                    vue.$nextTick(function () {
                        $("li input").each(function () {
                            $(this).hide();
                        });
                        ResetItemRecords(vue);
                        parent.ResizeAzModal();
                    });
                } else {
                    toastr.error(res.message);
                }
                parent.HideAzLoading();
            },
            error: function (err) {
                parent.HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    }
}

/**
 * 初始保养记录中保养项目记录列表
 */
function ResetItemRecords(vue) {
    vue.record.ItemRecords = [];
    for (var idx in vue.record.TemplateForm.Items) {
        var record = {
            ItemID: vue.record.TemplateForm.Items[idx].ID,
            IsOk: -1,
            Remark: ""
        }
        vue.record.ItemRecords.push(record);
    }
}

/**
 * 设置保养项目记录操作结果
 */
function ItemRecordCheck(vue, index, isPass) {
    var liTag = "#itemRecord" + index;
    var inputTag = "#itemRemark" + index;

    vue.record.ItemRecords[index].IsOk = isPass;
    if (isPass == true) {
        vue.record.ItemRecords[index].Remark = "";
        $(liTag).addClass("list-group-item-success");
        $(liTag).removeClass("list-group-item-danger");
        $(inputTag).val("");
        $(inputTag).slideUp();
    } else {
        $(liTag).removeClass("list-group-item-success");
        $(liTag).addClass("list-group-item-danger");
        $(inputTag).slideDown();
    }
    parent.ResizeAzModal();
}

/**
 * 保养项目不通过时，记录处理方法及结果。
 */
function ItemRecordRemark(vue, index, remark) {
    var inputTag = "#itemRemark" + index;
    vue.record.ItemRecords[index].Remark = remark;
    $(inputTag).val(remark);
}

/**
 * 清空信息
 */
function ResetForm(vue) {
    vue.record = {                   
        BaseInfo: {},
        Equipment: {
            BaseInfo: {},
            MaintainInfo: {}
        },
        TemplateForm: {
            BaseInfo: {},
            Items: []
        },
        ItemRecords: [],
        CheckerInfo: {},
        ApproverInfo: {}
    };
    vue.templateFormList = [];
    vue.$nextTick(function () {
        parent.ResizeAzModal();
    });
}

/**
 * 检查保养记录信息正确性
 */
function CheckMaintainRecode(vue) {
    if (!CheckRecordDate(vue)) {
        toastr.error("请选择保养日期Please select the maintenance date。")
        return false;
    } else if (!CheckEquipment(vue)) {
        toastr.error("请确认设备信息是否完整正确Please confirm whether the equipment information is complete and correct。")
        return false;
    } else if (!CheckCheckerInfo(vue)) {
        toastr.error("请确认保养员信息是否完整正确Please confirm whether the maintenance personnel information is complete and correct。")
        return false;
    } else if (!CheckApproverInfo(vue)) {
        toastr.error("请确认设备是否有管理员Please confirm whether the device has an administrator。")
        return false;
    } else if (!CheckMaintainItems(vue)) {
        toastr.error("请填写所有保养项目（不通过项目请填写处理方法及结果）Please fill in all maintenance items (please fill in the treatment methods and results if the items fail)。");
        return false;
    } else {
        return true;
    }
}

/**
 * 检查保养时间
 */
function CheckRecordDate(vue) {
    $("#recordDate").removeClass("has-error");
    if (!vue.record.BaseInfo.RecordDate) {
        $("#recordDate").addClass("has-error");
        return false;
    } else if (vue.record.BaseInfo.RecordDate.length == 0) {
        $("#recordDate").addClass("has-error");
        return false;
    }
    return true;
}

/**
 * 检查保养员信息是否正确
 */
function CheckCheckerInfo(vue) {
    $("#checkerName").removeClass("has-error");
    if (!vue.record.CheckerInfo) {
        $("#checkerName").addClass("has-error");
        return false;
    }
    return true;
}

/**
 * 检查管理（签核）员信息是否正确
 */
function CheckApproverInfo(vue) {
    $("#approverName").removeClass("has-error");
    if (!vue.record.ApproverInfo) {
        $("#approverName").addClass("has-error");
        return false;
    }
    return true;
}

/**
 * 检查保养记录信息中设备信息是否正确
 */
function CheckEquipment(vue) {
    $("#equipmentCode").removeClass("has-error");
    if (!vue.record.Equipment.BaseInfo.Name) {
        $("#equipmentCode").addClass("has-error");
        return false;
    } else if (vue.record.Equipment.BaseInfo.Name.length == 0) {
        $("#equipmentCode").addClass("has-error");
        return false;
    }
    return true;
}

/**
 * 检查保养记录信息中保养项目是否已填写，默认值为-1
 */
function CheckMaintainItems(vue) {
    for (var idx in vue.record.ItemRecords) {
        if (vue.record.ItemRecords[idx].IsOk < 0) {
            return false;
        } else if (vue.record.ItemRecords[idx].IsOk == 0) {
            if (vue.record.ItemRecords[idx].Remark.length == 0)
                return false;
        }
    }
    return true;
}

/**
 * Android调用方法，设置设备编号
 */
function AndroidSetEquipmentCode(code) {
    toastr.success(code);
    recordFormVue.record.Equipment.BaseInfo.Code = code;
}